package com.mephi.oshs.model.interpreter.impl;

import com.mephi.oshs.model.interpreter.api.IContext;
import com.mephi.oshs.model.interpreter.api.IExpression;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class VariableExpression implements IExpression {
    private final Object lookup;
    private final String methodName;

    public VariableExpression(final Object newLookup, final String newMethodName) {
        lookup = newLookup;
        methodName = newMethodName;
    }

    public void interpret(final IContext c) {
        try {
            final Object source = c.get(lookup);
            if (source != null) {
                final Method method = source.getClass().getMethod(methodName);
                final Object result = method.invoke(source);
                c.addVariable(this, result);
            }
        } catch (NoSuchMethodException ignored) {
        } catch (IllegalAccessException ignored) {
        } catch (InvocationTargetException ignored) {
        }
    }
}